package com.woniuxy.service.impl;

import com.woniuxy.entity.SysTeam;
import com.woniuxy.mapper.SysDoctorTeamMapper;
import com.woniuxy.mapper.SysTeamMapper;
import com.woniuxy.service.SysTeamService;
import com.woniuxy.util.ResponseEnum;
import com.woniuxy.util.ResponseUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 系统团队服务实现类
 * 实现系统团队相关的业务逻辑
 */
@Service
public class SysTeamServiceImpl implements SysTeamService {
    @Resource
    private SysTeamMapper sysTeamMapper;
    @Resource
    private SysDoctorTeamMapper sysDoctorTeamMapper;

    /**
     * 根据ID查询系统团队
     * @param id 团队ID
     * @return 返回指定ID的团队信息
     */
    @Override
    public ResponseUtil findById(Integer id) {
        SysTeam byId = sysTeamMapper.findById(id);
        return byId != null ? ResponseUtil.get(ResponseEnum.OK,byId)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }

    /**
     * 更新系统团队状态
     * @param id 团队ID
     * @param status 团队状态
     * @return 返回更新操作的响应结果
     */
    @Override
    public ResponseUtil updateSysTeam(Integer id ,Integer status) {
        Integer updateSysTeam = sysTeamMapper.updateSysTeam(id,status);
        return updateSysTeam > 0 ? ResponseUtil.get(ResponseEnum.OK)
                : ResponseUtil.get(ResponseEnum.FAIL);
    }
    /**
     * 删除系统团队
     * @param id 团队ID
     * @return 返回删除操作的响应结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseUtil deleteSysTeam(Integer id) {
        Integer deleteSysTeam = sysTeamMapper.deleteSysTeam(id);
        if (deleteSysTeam<=0){
            throw new RuntimeException("团队删除失败");
        }
        Integer integer = sysDoctorTeamMapper.deleteDoctorTeam(id);
        if (integer<=0){
            throw new RuntimeException("删除失败");
        }
        return ResponseUtil.get(ResponseEnum.OK);
    }
    /**
     * 添加新的系统团队
     * @param sysTeam 系统团队对象
     * @return 返回添加操作的响应结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseUtil addSysTeam(SysTeam sysTeam) {
        Integer integer = sysTeamMapper.addSysTeam(sysTeam);
        if (integer<=0){
            throw new RuntimeException("团队添加失败");
        }
        Integer addDoctorTeam = sysDoctorTeamMapper.addDoctorTeam(sysTeam.getLeaderId(),sysTeam.getId());
        if (addDoctorTeam<=0){
            throw new RuntimeException("队长绑定失败");
        }
        return ResponseUtil.get(ResponseEnum.OK);
    }
    
    /**
     * 查询所有团队（排除指定医生已加入的团队）
     * @param doctorId 医生ID
     * @return 返回可加入的团队列表
     */
    @Override
    public ResponseUtil findAllTeam(Integer doctorId) {
        List<SysTeam> allTeam = sysTeamMapper.findAllTeam(doctorId);
        return allTeam!=null?ResponseUtil.get(ResponseEnum.OK,allTeam)
                :ResponseUtil.get(ResponseEnum.FAIL);
    }
}
